package com.imoblife.brainwavestus.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import junit.framework.Assert;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import com.googleplay.billing.Consts.PurchaseState;
import com.googleplay.billing.Security;
import com.googleplay.billing.Security.VerifiedPurchase;
import com.imoblife.brainwavestus.database.SQLiteManager;
import com.imoblife.brainwavestus.database.SQLiteManager.DownTaskTable;
import com.imoblife.brainwavestus.database.SycSqlite;
import com.imoblife.brainwavestus.model.Constant;
import com.imoblife.brainwavestus.obpurchaseSystem.OBpurchaseSystem;
import com.imoblife.brainwavestus.oldDownloadFrame.Commmand;
import com.imoblife.brainwavestus.oldDownloadFrame.DownLoadItemPragrame;
import com.imoblife.brainwavestus.product.Product;
import com.imoblife.brainwavestus.product.ProductInfo;
import com.imoblife.brainwavestus.product.Store;
import com.imoblife.brainwavestus.service.DownLoadSchedulerSystem;
import com.imoblife.brainwavestus.users.UserAccount;
import com.imoblife.brainwavestus.users.UsersUtil;

public class MakePurchaseStateChenge {
	public static final String subscription_id = "brainwave_yearly";
	public static final String TAG = "MakePurchaseStateChenge";

	public static void transactionsChange(
			ArrayList<Security.VerifiedPurchase> purchases, Context context) {

		try {
			Assert.assertNotNull(context);
			// ���˵�
			if (purchases == null) {
				DebugUtil.debug(TAG, "��õ��˵�Ϊnull");

				// �˵�ID}������ ȷ��Ϊ�ָ��˵��¼�
			} else if (purchases.size() > 1) {// �ָ�

				DebugUtil.debug(TAG, "�ָ��˵�>> �˵���" + purchases.size());

				for (VerifiedPurchase verifiedPurchase : purchases) {

					if ((verifiedPurchase != null)
							&& verifiedPurchase.purchaseState == PurchaseState.PURCHASED
							&& verifiedPurchase.productId
									.equals(subscription_id)) {

						
						SycSqlite database = SQLiteManager
								.getDatabaseInstence(context);

						ContentValues values = new ContentValues();
						values.put(DownTaskTable.STATE,
								DownLoadItemPragrame.DOWN_STATE_CANCEL);
						
						database.update(
								DownTaskTable.TB_NAME,
								values,
								DownTaskTable.STATE + "=?",
								new String[] { DownLoadItemPragrame.DOWN_STATE_NOT_ENBLE
										+ "" });
						// 3 ���涩���û����
						saveSubsciptionState(context);

						// 4���涩��ʱ��
						saveStartTime(context, verifiedPurchase.purchaseTime);

						// 5 ˢ�¶���ʱ��㲥
						Intent Intent = new Intent(
								UsersUtil.UPDATE_STATEVIEW_MYSUBSCRIPTION);
						context.sendBroadcast(Intent);

						// 6ˢ��������
						Intent updateLibraryIntent = new Intent(
								UsersUtil.UPDATE_LIBRERY_CATEGOTY);
						context.sendBroadcast(updateLibraryIntent);

						return;

					}

				}

				if (isPastSubsciption(context)) {
					// ȡ����

					DebugUtil.debug(TAG, "�ָ��˵� �û�ȡ������Ϊ");
					doCancalSubs(purchases, context);

				} else {
					// �Ƕ����ҹ�����

					DebugUtil.debug(TAG, "�Ƕ����ҹ�����");

					for (VerifiedPurchase verifiedPurchase : purchases) {

						makeState(
								verifiedPurchase.purchaseState,
								tansformToTaskName(verifiedPurchase.productId,
										context), context);
					}

				}

			} else if (purchases.size() > 0) {// ������Ϊ

				DebugUtil.debug(TAG, "������Ϊ");

				if (subscription_id.equals(purchases.get(0).productId)
						&& (purchases.get(0).purchaseState == PurchaseState.PURCHASED)) {

					DebugUtil.debug(TAG, "ȫ��������Ϊ");
					SycSqlite database = SQLiteManager
							.getDatabaseInstence(context);
					ContentValues values = new ContentValues();
					values.put(DownTaskTable.STATE,
							DownLoadItemPragrame.DOWN_STATE_CANCEL);
					database.update(
							DownTaskTable.TB_NAME,
							values,
							DownTaskTable.STATE + "=?",
							new String[] { DownLoadItemPragrame.DOWN_STATE_NOT_ENBLE
									+ "" });
					saveSubsciptionState(context);
					saveStartTime(context, purchases.get(0).purchaseTime);

				} else {

					DebugUtil.debug(TAG, "���������Ϊ");
					makeState(
							purchases.get(0).purchaseState,
							tansformToTaskName(purchases.get(0).productId,
									context), context);
				}

			} else {

				DebugUtil.debug(TAG, "��õ��˵�Ϊ<=0");

			}

		} catch (Exception e) {

			ProductUtil.appandDebugInfo(context, e.getMessage());
			ProductUtil.sendEmail(context);

		}

	}

	private static void doCancalSubs(
			final ArrayList<Security.VerifiedPurchase> purchases,
			final Context mContext) {

		new Thread() {

			public void run() {
				HashMap<String, PurchaseState> purchasesMap = new HashMap<String, PurchaseState>();

				DebugUtil.debug(TAG, "�ָ� Tapjoy �˵� ��ʼ");

				// ��ȡT�˵�
				UserAccount user = new UserAccount(mContext);
				UsersUtil util = new UsersUtil(mContext);
				String result;
				String[] serverBillings;
				if (user.getIsLogin()) {
					result = OBpurchaseSystem.getOBpurchaseSystem(mContext)
							.HttpGetAllMusicBill();
					if (result != null && !result.equals("1")) {

						util.setIsGetMusicBillSuccess(mContext, true);

						serverBillings = result.split("\\|");

						for (String tjId : serverBillings) {

							if (tjId.length() > 2) {

								ArrayList<String> arrayList = tansformToTaskName(
										tjId.trim(), mContext);

								for (String productId : arrayList) {
									purchasesMap.put(productId,
											PurchaseState.PURCHASED);
								}
							}
						}
						DebugUtil.debug(TAG, "Tapjoy �ָ� TJ �˵� �ɹ�");
					} else {
						DebugUtil.debug(TAG, "Tapjoy �ָ�TJʧ��");
					}

				}

				// �ָ�google�˵�

				DebugUtil.debug(TAG, "�ָ�google�˵�");

				for (VerifiedPurchase verifiedPurchase : purchases) {

					if (verifiedPurchase.purchaseState == PurchaseState.PURCHASED) {

						ArrayList<String> arrayList = tansformToTaskName(
								verifiedPurchase.productId, mContext);

						for (String productId : arrayList) {
							purchasesMap
									.put(productId, PurchaseState.PURCHASED);
						}

					}

				}

				StringBuffer purchaseSql = new StringBuffer();
				purchaseSql.append("(");
				Iterator<Entry<String, PurchaseState>> iter = purchasesMap
						.entrySet().iterator();
				while (iter.hasNext()) {
					Entry<String, PurchaseState> entry = iter.next();
					purchaseSql.append("'" + entry.getKey() + "'");
					purchaseSql.append(",");
				}

				purchaseSql.replace(purchaseSql.length() - 1,
						purchaseSql.length(), ")");

				DebugUtil.debug("transactionsChange", purchaseSql.toString());

				SycSqlite database = SQLiteManager
						.getDatabaseInstence(mContext);
				ContentValues values = new ContentValues();
				values.put(DownTaskTable.STATE,
						DownLoadItemPragrame.DOWN_STATE_NOT_ENBLE);
				// 1�ص�Ȩ��
				database.update(
						DownTaskTable.TB_NAME,
						values,
						DownTaskTable.NAME + " NOT IN "
								+ purchaseSql.toString(), null);
				values.put(DownTaskTable.STATE,
						DownLoadItemPragrame.DOWN_STATE_START);
				// 2 ���˵���û��Ȩ�޵Ŀ���Ȩ��
				database.update(DownTaskTable.TB_NAME, values,
						DownTaskTable.NAME + " IN " + purchaseSql.toString()
								+ " and " + DownTaskTable.STATE + "="
								+ DownLoadItemPragrame.DOWN_STATE_NOT_ENBLE,
						null);
				Intent updateSubscriptionIntent = new Intent(
						UsersUtil.UPDATE_STATEVIEW_SUBSCRIPTION);
				mContext.sendBroadcast(updateSubscriptionIntent);

				clearSubsciption(mContext);
			}
		}.start();

	}

	public static void saveStartTime(Context context, long startTime) {

		SharedPreferences preferences = context.getSharedPreferences(
				"Subsciption", 0);
		preferences.edit().putLong("startTime", startTime).commit();
	}

	public static long getStartTime(Context context) {
		SharedPreferences preferences = context.getSharedPreferences(
				"Subsciption", 0);

		return preferences.getLong("startTime", 0);
	}

	public static void saveSubsciptionState(Context context) {

		SharedPreferences preferences = context.getSharedPreferences(
				"Subsciption", 0);
		preferences.edit().putBoolean("isPast", true).commit();
	}

	public static boolean isPastSubsciption(Context context) {
		SharedPreferences preferences = context.getSharedPreferences(
				"Subsciption", 0);

		return preferences.getBoolean("isPast", false);
	}

	public static void clearSubsciption(Context context) {

		SharedPreferences preferences = context.getSharedPreferences(
				"Subsciption", 0);
		preferences.edit().clear().commit();
	}

	public static void purchaseStateChange(Context context,
			PurchaseState purchaseState, String itemId, int quantity,
			long purchaseTime, String developerPayload, int size) {
		makeState(purchaseState, tansformToTaskName(itemId, context), context);
	}
	
	
	
	//老版本的实现机制，仅作为参考使用，请使用beginDownloadProduct代替此方法
	public static void confirmPurchaseState(Context context, String itemId) {

		ArrayList<String> arrayList = tansformToTaskName(itemId, context);
		String downloadTask = null;

		for (String string : arrayList) {
			DebugUtil.debug(TAG, " makeState�Ѿ������Ʒ" + string);
			if (getTaskState(string, context) == DownLoadItemPragrame.DOWN_STATE_NOT_ENBLE) {
				setTaskState(string, DownLoadItemPragrame.DOWN_STATE_START,
						context);
				downloadTask = string;
			}
		}

		if (downloadTask != null) {
			Commmand.makeMusicDownloadCommand(downloadTask, context);
		}
	}

	public static void confirmProductState(Context context, String itemId) {

		ArrayList<String> arrayList = tansformToTaskName(itemId, context);
		// Assert.assertTrue(arrayList.size() > 0);
		String downloadTask = null;
		for (String string : arrayList) {
			DebugUtil.debug(TAG, " makeState�Ѿ������Ʒ" + string);
			if (getTaskState(string, context) == DownLoadItemPragrame.DOWN_STATE_NOT_ENBLE) {
				setTaskState(string, DownLoadItemPragrame.DOWN_STATE_CANCEL,
						context);
				downloadTask = string;
			}
		}
		// if (downloadTask != null) {
		// Commmand.makeMusicDownloadCommand(downloadTask, context);
		// }
	}

	public static void confirmProductState2(Context context, String itemId) {

		ArrayList<String> arrayList = tansformToTaskName(itemId, context);
		// Assert.assertTrue(arrayList.size() > 0);
		String downloadTask = null;
		for (String string : arrayList) {
			DebugUtil.debug(TAG, " makeState�Ѿ������Ʒ" + string);
			if (getTaskState(string, context) == DownLoadItemPragrame.DOWN_STATE_NOT_ENBLE) {
				setTaskState(string, DownLoadItemPragrame.DOWN_STATE_CANCEL,
						context);
				downloadTask = string;
			}
		}
		if (downloadTask != null) {
			Commmand.makeMusicDownloadCommand(downloadTask, context);
		}
	}

	private static ArrayList<String> tansformToTaskName(String itemId,
			Context context) {

		itemId = productIdTansformTaskName(itemId);
		DebugUtil.debug(TAG, "tansformToTaskName item" + itemId);
		ArrayList<String> list = new ArrayList<String>();

		// �ٶ�����������
		SycSqlite database = SQLiteManager.getDatabaseInstence(context);
		Cursor cursor = database.query(DownTaskTable.TB_NAME,
				new String[] { DownTaskTable.NAME }, DownTaskTable.NAME + "=?",
				new String[] { itemId + ".music" }, null, null, null);

		// ��ô������������
		if (cursor != null && cursor.getCount() > 0) {
			// ȷ��Ϊ������
			DebugUtil.debug(TAG, "ȷ��Ϊ������" + itemId);
			list.add(itemId + ".music");
			cursor.close();
			return list;
		}

		// ȷ��Ϊ����
		cursor = database.query(DownTaskTable.TB_NAME,
				new String[] { DownTaskTable.NAME }, DownTaskTable.NAME
						+ " Like " + "'%.music'" + " And "
						+ DownTaskTable.PARENT + "=?", new String[] { itemId },
				null, null, null);

		if (cursor != null && cursor.getCount() > 0) {

			while (cursor.moveToNext()) {
				DebugUtil.debug(TAG,
						"�ϼ����" + itemId + "�ϼ�����" + cursor.getString(0));
				list.add(cursor.getString(0));
			}
			cursor.close();
		}

		return list;

	}

	public static int getTaskState(String taskName, Context context) {

		DBUtil db = new DBUtil(context);
		
		int intdownloadState = Constant.INT_DOWN_STATE_NOT_ENBLE;
		
		intdownloadState 
				= db.openForRead().getDownTaskState(taskName);
		db.closeDb();
		
		DebugUtil.debug(TAG, "strDownloadstate: " + intdownloadState);
			
		return intdownloadState;
	}

	private static void setTaskState(String name, int state, Context context) {

		SycSqlite database = SQLiteManager.getDatabaseInstence(context);

		ContentValues values = new ContentValues();

		values.put(DownTaskTable.STATE, state);

		values.put(DownTaskTable.CHENGETIME, System.currentTimeMillis());

		database.update(SQLiteManager.DownTaskTable.TB_NAME, values,
				SQLiteManager.DownTaskTable.NAME + "=?", new String[] { name });
	}

	private static void makeState(PurchaseState purchaseState,
			ArrayList<String> list, Context context) {
		final String marketBilling = "marketBilling";
		if (purchaseState == PurchaseState.PURCHASED) {

			String downloadTask = null;

			for (String string : list) {
				DebugUtil.debug(marketBilling, " makeState�Ѿ������Ʒ" + string);
				if (getTaskState(string, context) == DownLoadItemPragrame.DOWN_STATE_NOT_ENBLE) {
					setTaskState(string,
							DownLoadItemPragrame.DOWN_STATE_CANCEL, context);
					downloadTask = string;
				}
			}

			if (downloadTask != null) {
				Commmand.makeMusicDownloadCommand(downloadTask, context);
			}

		} else if (purchaseState == PurchaseState.REFUNDED) {

			for (String string : list) {
				DebugUtil.debug(marketBilling, " makeState�Ѿ��˿�Ĳ�Ʒ" + string);
				setTaskState(string, DownLoadItemPragrame.DOWN_STATE_NOT_ENBLE,
						context);
			}
		}

	}

	/**
	 * ���һ���Ʒ�Ƿ��ѹ���
	 * 
	 * @param context
	 * @param productName
	 *            market �ϵĲ�Ʒ��
	 * @return ����Ѿ����� �򷵻�true,���� false;
	 */
	public static boolean isPurchased(Context context, String productName) {
		ArrayList<String> productList = tansformToTaskName(productName, context);

		for (String string : productList) {
			if (getTaskState(string, context) != DownLoadItemPragrame.DOWN_STATE_NOT_ENBLE) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 
	 * @param taskName
	 * @param context
	 */
	public static void makeMusicDownloadCommand(String taskName, Context context) {
		Intent intent = new Intent(
				DownLoadSchedulerSystem.ACT_SCHEDULER_DOWNLAOD);

		intent.putExtra("command",
				DownLoadSchedulerSystem.COMMAND_RECAIVER_MUSIC_DOWNLOAD);
		intent.putExtra(
				DownLoadSchedulerSystem.COMMAND_RECAIVER_MUSIC_DOWNLOAD,
				taskName);
		context.sendBroadcast(intent);
	}

	/**
	 * �� marketID ת���� ��ݿ��������
	 * 
	 * @param productId
	 *            ��market �ϵ�ID
	 * @return ������ݿ��ID
	 */
	public static String productIdTansformTaskName(String productId) {

		// // �ܷ�ŭ�Ĵ��� ��ݿ��marketID ������
		// if (productId.equals("esp_psychic")) {
		// return "ESP Psychic";
		// } else if (productId.equals("iq_increase")) {
		// return "IQ Increase";
		// } else {
		// StringBuffer stringBuffer = new StringBuffer(productId);
		// for (int i = 0; i < stringBuffer.length() - 1; i++) {
		// if (i == 0) {
		// char c = stringBuffer.charAt(i);
		// c -= 32;
		// stringBuffer.setCharAt(i, c);
		// } else if (stringBuffer.charAt(i) == '_') {
		// char c = stringBuffer.charAt(i + 1);
		// c -= 32;
		// stringBuffer.setCharAt(i + 1, c);
		// stringBuffer.setCharAt(i, ' ');
		// }
		// }
		// return stringBuffer.toString();

		return productId;

	}

}
